module.exports = {
  up: async (queryInterface, Sequelize) => {
    await queryInterface.createTable('tenant_permissions', {
      id: {
        type: Sequelize.UUID,
        defaultValue: Sequelize.UUIDV4,
        primaryKey: true,
      },
      tenant_id: {
        type: Sequelize.UUID,
        allowNull: false,
        references: {
          model: 'tenants',
          key: 'id',
        },
        onUpdate: 'CASCADE',
        onDelete: 'CASCADE',
      },
      permission_id: {
        type: Sequelize.UUID,
        allowNull: false,
        references: {
          model: 'permissions',
          key: 'id',
        },
        onUpdate: 'CASCADE',
        onDelete: 'CASCADE',
      },
      source: {
        type: Sequelize.ENUM('plan', 'extra'),
        allowNull: false,
        defaultValue: 'plan',
        comment: '权限来源：plan-来自套餐，extra-额外授予',
      },
      granted_by: {
        type: Sequelize.UUID,
        allowNull: true,
        references: {
          model: 'users',
          key: 'id',
        },
        onUpdate: 'CASCADE',
        onDelete: 'SET NULL',
        comment: '授权人ID',
      },
      granted_at: {
        type: Sequelize.DATE,
        allowNull: true,
        comment: '授权时间',
      },
      expires_at: {
        type: Sequelize.DATE,
        allowNull: true,
        comment: '过期时间（可选）',
      },
      created_at: {
        type: Sequelize.DATE,
        allowNull: false,
      },
      updated_at: {
        type: Sequelize.DATE,
        allowNull: false,
      },
    });

    // 添加唯一索引，确保租户-权限组合唯一
    await queryInterface.addIndex('tenant_permissions', ['tenant_id', 'permission_id'], {
      unique: true,
      name: 'tenant_permissions_tenant_id_permission_id_unique',
    });

    // 添加索引
    await queryInterface.addIndex('tenant_permissions', ['tenant_id']);
    await queryInterface.addIndex('tenant_permissions', ['permission_id']);
    await queryInterface.addIndex('tenant_permissions', ['source']);
    await queryInterface.addIndex('tenant_permissions', ['expires_at']);
  },

  down: async (queryInterface) => {
    await queryInterface.dropTable('tenant_permissions');
  },
};

